﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace DeploymentMaxLib
{
    public static class Common
    {
        public static ActionResult ExecuteBatch(string pCommand, bool pWaitForExit, out string pErrorLog, out string pOutLog)
        {
            var tResult = new ActionResult();

            var tBatchFile = string.Format(@".\{0}.bat", Guid.NewGuid().ToString("P"));

            using (Process process = new Process())
            {
                try
                {
                    using (System.IO.StreamWriter sw = new StreamWriter(tBatchFile))
                    {
                        sw.Write(pCommand);
                        sw.Close();
                    }

                    process.StartInfo.ErrorDialog = false;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    process.StartInfo.FileName = tBatchFile;
                    process.StartInfo.RedirectStandardError = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.StandardErrorEncoding = Encoding.Default;
                    process.StartInfo.StandardOutputEncoding = Encoding.Default;
                    process.Start();

                    if (pWaitForExit)
                    {
                        process.WaitForExit();
                    }
                }
                catch (Exception exc)
                {
                    if (process != null) { process.Kill(); }
                    tResult.AddResult(exc);
                }

                System.IO.File.Delete(tBatchFile);

                StreamReader standardError = process.StandardError;
                StreamReader standardOutput = process.StandardOutput;

                pErrorLog = standardError.ReadAllText();
                pOutLog = standardOutput.ReadAllText();
            }

            return tResult;
        }
    }
}
